// nutui
import { Button, Input, Toast } from "@nutui/nutui-react-taro";
import { Form } from "@nutui/nutui-react-taro";

// taro
import Taro, { useShareAppMessage } from "@tarojs/taro";
import { View } from "@tarojs/components";

// react
import { useEffect, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { changeUser, phoneOpenid, storeUser } from "@/redux/userSlice";


import {  ApiMemberInfo,  ApiSendCaptcha, ApiUpdateMemberMobile } from "../../utils/api";
import "./model.scss";

import WXBizDataCrypt from "../../../Node/WXBizDataCrypt";
import config from "../../../config/wx";
import QQMapWX from "../../xcx-sdk/qqmap-wx-jssdk"
import { Map } from '@tarojs/components';  

const phone = () => {
  useShareAppMessage((res) => {
    if (res.from === "button") {
      // 来自页面内转发按钮
      console.log(res.target);
    }

    return {
      title: "东进会员",
      path: "pages/home/index", //?id=123
      imageUrl: "../../assets/home.jpg",
      // imageUrl,
    };
  });
  // 表单控件
  const [form] = Form.useForm();
  const dispatch = useDispatch();

  // const storeMemberId = useSelector(storeMember_id);
  const user = useSelector(storeUser);
  const myOpenid = useSelector(phoneOpenid);

  const [registerForm, SetRegisterForm] = useState({
    openid: Taro.getStorageSync("openid") || "",
    sessionKey: Taro.getStorageSync("sessionKey") || "",
  });

  // 用户手机号等
  const [formData, setFormData] = useState({
    name: "",
    sex: 0,
    birthday: null,
    mobile: "",
    captcha: "",
    plate_number: "",
  });

  // 检查并登录的member_id
  const [member_id, setMember_id] = useState(-1);
  // 验证码
  const [sendCode, setSendCode] = useState(false);
  const [num, setNum] = useState(60);
  const [phone, setPhone] = useState("");
  // 修改user对象属性值
  const handleFieldChange = <K extends keyof RootObject>(
    fieldName: K,
    value: RootObject[K]
  ) => {
    // console.log(fieldName, value);
    setFormData((prevData) => ({
      ...prevData,
      [fieldName]: value,
    }));
  };

  //  user对象里的属性名 属性值
  const handleNameInputChange = (
    type: keyof RootObject,
    value: RootObject[keyof RootObject]
  ) => {
    // console.log("type", type);
    handleFieldChange(type, value);
    // console.log("formData", formData);
  };

  // 获取会员详情信息
  const getMemberInfo = async (member_id2?: number) => {
    let my_member_id = member_id2 ? member_id2 : member_id;
    // console.log(my_member_id, "my_member_id");
    if (!myOpenid) {
      console.log("需重新进入");
      // navigate("/");
      Taro.reLaunch({
        url: "/pages/home/index",
      });
      return;
    }
    // console.log(my_member_id, "my_member_id");
    // 请求用户信息

    // 校验是否有
    let resInfo;
    // console.log(user, "user");
    if (!user.mobile) {
      resInfo = await ApiMemberInfo(my_member_id);
      if (resInfo.code != 0) {
        console.log("请求用户信息失败");
        return;
      }
      // 没有请求,存仓库
      dispatch(changeUser(resInfo.data));
      const { mobile } = resInfo.data;
      // 更新
      setPhone(mobile);
    } else {
      // 从仓库读取
      // console.log(user, "user");
      // 更新用户对象
      const { mobile } = user;
      setPhone(mobile);
    }
    // form.setFieldsValue(formData);
    return resInfo;
  };

  // 确定注册手机
  const determine = async () => {
    //校验失败
    // console.log(formData, 2);
    if (formData.mobile == "") {
      Toast.show("test", { title: "请先填写手机号", duration: 1.5 });
      return;
    }
    // if (!isCodeSent) {
    //   // setSendCode(false);
    //   Toast.show("test", { title: "请先获取验证码", duration: 2 });
    //   return;
    // }
    if (formData.captcha == "") {
      Toast.show("test", { title: "请先填写验证码", duration: 1 });
      return;
    }
    if (phone == formData.mobile) {
      Toast.show("test", { title: "与原手机号一致", duration: 1.5 });
      return;
    }
    // 是否校验成功

    // Toast.show({ content: "校验失败" });
    console.log(formData.mobile, formData.captcha);
    // return;
    //校验成功
    try {
      const res = await ApiUpdateMemberMobile(
        formData.mobile,
        formData.captcha
      );
      // openToast("success", "修改手机号成功");
      // SetShowToast(true);
      if (res.code == 0) {
        Taro.showToast({
          title: "修改手机号成功",
          icon: "success",
        });
        dispatch(
          changeUser({
            ...user,
            mobile: formData.mobile,
          })
        );
        setTimeout(() => {
          Taro.reLaunch({
            url: "/pages/home/index",
          });
        }, 800);
      } else {
        Taro.showToast({
          title: res.msg,
          icon: "error",
        });
      }
      // navigate("/home");
      // Taro.reLaunch({
      //   url: "/pages/home/index",
      // });
    } catch (error: any) {
      // Toast.show({ content: error.msg || "验证码有误" });
      // Toast.show("fail", { title: error.msg || "验证码有误", duration: 2 });
      // openToast("fail", error.msg || "验证码有误");
      // SetShowToast(true);
      Taro.showToast({
        title: error.msg || "验证码有误",
        icon: "error",
      });
      // setSendCode(false);
    }
  };

  // 在组件中添加 ref
  const timerRef = useRef<number | null>(null);
  // 在 useEffect 中清除上一次的定时器
  useEffect(() => {
    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
    };
  }, []);

  useEffect(() => {
    // 获取用户信息
    // getCode();
    // init();
    getMemberInfo();
    // 检测是否注册过
  }, []);

  const API_KEY = "	CSHBZ-X7S3G-A2FQI-QNZSQ-DJ4UJ-HEB74"
  // 创建一个ref来保存地图实例  
  const mapCtx = useRef<MapContext | null>(null);  
  // 假设东莞的某个区域的经纬度中心点  
  const dongguanCenter = {  
    latitude: 23.099994, // 东莞市中心的大致纬度  
    longitude: 113.758561, // 东莞市中心的大致经度  
  };  
  // 标记点数据，可以是多个标记点的数组  
  const markers = [  
    {  
      id: 1,  
      latitude: dongguanCenter.latitude,  
      longitude: dongguanCenter.longitude,  
      title: '东莞市中心',  
    },  
    // 在这里可以添加更多的标记点  
  ];  
  // 初始化地图  
  useEffect(() => {  
    const initMap = async () => {  
      try {  
        // 获取地图上下文  
        const ctx = Taro.createMapContext('myMap');  
        // 初始化地图  
        await mapCtx.current?.initMap({  
          key: API_KEY,  
          version: '1.0',  
        });  
  
        // 在这里可以添加其他的地图功能，比如添加标记等  
        // 例如：ctx.addMarker({ ... })  
  
      } catch (error) {  
        console.error('初始化地图失败:', error);  
      }  
    };  
  
    initMap();  
  }, []);  

  // 更新界面
  // sendCode
  // 挂载页面
  useEffect(() => {
    form.setFieldsValue(formData);
  }, [formData, form]);

  return (
    <View>
      <View className="container">  
      <Map  
        id="myMap"  
        style={{ width: '100%', height: '500px' }}  
        showLocation
        latitude={dongguanCenter.latitude}  
        longitude={dongguanCenter.longitude}  
        scale={14} // 地图缩放级别  
        markers={markers}  // 你的标记点数据  
      />  
    </View>  
      <Toast id="test" />
      {/* <Toast
        msg={state.msg}
        visible={showToast}
        type={state.type}
        onClose={() => {
          SetShowToast(false);
        }}
      /> */}
      <Form
        form={form}
        initialValues={{ ...formData }}
        divider
        labelPosition="left"
      >
      </Form>
    </View>
  );
};

export default phone;
